package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.AffixMapper;
import com.itheima.travel.pojo.Affix;
import com.itheima.travel.pojo.AffixExample;
import com.itheima.travel.req.AffixVo;
import com.itheima.travel.service.AffixService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class AffixServiceImpl implements AffixService {
    @Autowired
    private AffixMapper affixMapper;
    @Value("${upLoad.pathRoot}")
    private String pathRoot;

    /**
     * 文件上传
     * @param multipartFile 上传对象
     * @param affixVo 附件对象
     * @return
     * @throws IOException
     */
    @Override
    public AffixVo upLoad(MultipartFile multipartFile, AffixVo affixVo) throws IOException {
        if(EmptyUtil.isNullOrEmpty(multipartFile)){
            return null;
        }
        //获取文件真实名
        String originalFilename = multipartFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        //获取后缀名
        String suffixName = originalFilename.substring(index, originalFilename.length());
        //拼接成完整文件名
        String realName=UUID.randomUUID().toString()+suffixName;
        //将后缀名分装到对象中
        affixVo.setSuffix(suffixName);
        //文件存放文件夹
        String filePathStr = pathRoot + "/" + affixVo.getBusinessType();
        File file = new File(filePathStr);
        //判断文件夹是否存在，不存在则创建文件夹
        if(EmptyUtil.isNullOrEmpty(file)){
            file.mkdir();
        }
        //上传文件
        multipartFile.transferTo(file);
        String pathUrl = affixVo.getBusinessType() + "/" + realName;
        affixVo.setFileName(realName);
        affixVo.setPathUrl(pathUrl);
        int i = affixMapper.insert(BeanConv.toBean(affixVo, Affix.class));
        if(i>0){
            return affixVo;
        }
        return null;

    }

    /**
     * 绑定业务id
     * @param  affixVo 附件对象
     * @return
     */
    @Override
    public Boolean bindBusinessId(AffixVo affixVo) {
        int flag = affixMapper.updateByPrimaryKeySelective(BeanConv.toBean(affixVo, Affix.class));
        return flag>0;
    }

    /**
     * 根据业务id查询文件信息
     * @param  affixVo 附件对象
     * @return
     */
    @Override
    public List<AffixVo> findAffixByBusinessId(AffixVo affixVo) {
        if(EmptyUtil.isNullOrEmpty(affixVo)){
            return null;
        }
        AffixExample affixExample = new AffixExample();
        affixExample.createCriteria().andBusinessIdEqualTo(affixVo.getBusinessId());
        List<Affix> affixList = affixMapper.selectByExample(affixExample);
        return BeanConv.toBeanList(affixList,AffixVo.class);
    }
}
